<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模板生成 - DocuGen</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/style.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>
<body class="bg-light">
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-file-earmark-text me-2"></i>DocuGen
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/"><i class="bi bi-house me-1"></i>首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/document-generator"><i class="bi bi-file-earmark-text me-1"></i>文档生成</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/template-generator"><i class="bi bi-file-earmark-richtext me-1"></i>模板生成</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="modelDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="bi bi-gear me-1"></i>模型设置
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="modelDropdown">
                            <li><a class="dropdown-item model-switch" data-model="local" href="#"><i class="bi bi-cpu me-1"></i>本地模型</a></li>
                            <li><a class="dropdown-item model-switch" data-model="third_party" href="#"><i class="bi bi-cloud me-1"></i>第三方模型</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container py-4">
        <h1 class="mb-4 text-primary"><i class="bi bi-file-earmark-richtext me-2"></i>文档模板生成器</h1>
        
        <div class="row">
            <div class="col-lg-4">
                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0">
                            <i class="bi bi-1-circle me-2"></i>模板配置
                        </h5>
                    </div>
                    <div class="card-body">
                        <form id="templateForm">
                            <div class="mb-3">
                                <label for="templateType" class="form-label">模板类型</label>
                                <select class="form-select" id="templateType">
                                    <option value="">请选择模板类型</option>
                                    <option value="business_plan">商业计划书</option>
                                    <option value="research_report">研究报告</option>
                                    <option value="academic_paper">学术论文</option>
                                    <option value="product_proposal">产品提案</option>
                                    <option value="project_proposal">项目提案</option>
                                    <option value="user_manual">用户手册</option>
                                    <option value="technical_manual">技术手册</option>
                                    <option value="custom">自定义模板</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="templateName" class="form-label">模板名称</label>
                                <input type="text" class="form-control" id="templateName" placeholder="为你的模板命名">
                            </div>
                            
                            <div class="mb-3">
                                <label for="templatePurpose" class="form-label">模板用途</label>
                                <textarea class="form-control" id="templatePurpose" rows="3" placeholder="描述这个模板的用途和目标读者"></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label for="requiredSections" class="form-label">必需章节（每行一个）</label>
                                <textarea class="form-control" id="requiredSections" rows="4" placeholder="输入必须包含的章节，每行一个"></textarea>
                            </div>
                            
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary" id="generateTemplateBtn">
                                    <span class="spinner-border spinner-border-sm d-none" id="templateSpinner"></span>
                                    <i class="bi bi-magic me-2"></i>生成模板
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="card shadow-sm mb-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0">
                            <i class="bi bi-save me-2"></i>保存与导出
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <button class="btn btn-success w-100 mb-2" id="saveTemplateBtn" disabled>
                                <i class="bi bi-save me-2"></i>保存到我的模板
                            </button>
                        </div>
                        <div class="mb-3">
                            <button class="btn btn-primary w-100 mb-2" id="exportDocxBtn" disabled>
                                <i class="bi bi-file-earmark-word me-2"></i>导出为Word模板
                            </button>
                        </div>
                        <div class="mb-3">
                            <button class="btn btn-primary w-100" id="exportMdBtn" disabled>
                                <i class="bi bi-markdown me-2"></i>导出为Markdown
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-8">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0">
                            <i class="bi bi-2-circle me-2"></i>模板预览与编辑
                        </h5>
                    </div>
                    <div class="card-body">
                        <ul class="nav nav-tabs" id="templateTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="structure-tab" data-bs-toggle="tab" data-bs-target="#structure" type="button" role="tab">结构</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="preview-tab" data-bs-toggle="tab" data-bs-target="#preview" type="button" role="tab">预览</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="variable-tab" data-bs-toggle="tab" data-bs-target="#variables" type="button" role="tab">变量设置</button>
                            </li>
                        </ul>
                        <div class="tab-content mt-3" id="templateTabsContent">
                            <div class="tab-pane fade show active" id="structure" role="tabpanel">
                                <div id="templateStructure" class="p-3 bg-white border rounded">
                                    <div class="text-center py-5 text-muted">
                                        <i class="bi bi-file-earmark-text display-1"></i>
                                        <p class="mt-3">模板结构将在这里显示</p>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="preview" role="tabpanel">
                                <div id="templatePreview" class="p-3 bg-white border rounded">
                                    <div class="text-center py-5 text-muted">
                                        <i class="bi bi-eye display-1"></i>
                                        <p class="mt-3">预览将在这里显示</p>
                                    </div>
                                </div>
                            </div>
                            <div class="tab-pane fade" id="variables" role="tabpanel">
                                <div class="p-3 bg-white border rounded">
                                    <p class="text-muted mb-3">为模板设置变量，生成文档时将被替换为实际内容。</p>
                                    <div id="variablesList">
                                        <div class="text-center py-4 text-muted">
                                            <p>先生成模板，然后添加变量</p>
                                        </div>
                                    </div>
                                    <button class="btn btn-outline-primary mt-3" id="addVariableBtn" disabled>
                                        <i class="bi bi-plus-circle me-2"></i>添加变量
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 变量添加模态框 -->
    <div class="modal fade" id="variableModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加模板变量</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="variableForm">
                        <div class="mb-3">
                            <label for="variableName" class="form-label">变量名</label>
                            <input type="text" class="form-control" id="variableName" placeholder="例如: company_name">
                        </div>
                        <div class="mb-3">
                            <label for="variableDescription" class="form-label">描述</label>
                            <input type="text" class="form-control" id="variableDescription" placeholder="例如: 公司名称">
                        </div>
                        <div class="mb-3">
                            <label for="variableDefault" class="form-label">默认值（可选）</label>
                            <input type="text" class="form-control" id="variableDefault" placeholder="例如: XX公司">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveVariableBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-6">
                    <h5><i class="bi bi-file-earmark-text me-2"></i>DocuGen</h5>
                    <p>AI驱动的文档生成系统，让创作更高效。</p>
                </div>
                <div class="col-md-6 text-md-end">
                    <p class="mb-0">&copy; 2023 DocuGen. 保留所有权利。</p>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            // 存储生成的模板数据
            let templateData = null;
            let templateVariables = [];
            let currentTemplateId = null;
            
            // 当前模型类型
            let currentModel = 'third_party';
            
            // 模板类型示例描述
            const templateExamples = {
                'business_plan': '商业计划书通常包括：执行摘要、公司描述、市场分析、组织结构、产品线、营销策略、财务预测和资金需求等章节。',
                'research_report': '研究报告通常包括：摘要、研究背景、文献综述、研究方法、数据分析、调查结果、结论和建议等章节。',
                'academic_paper': '学术论文通常包括：摘要、引言、文献综述、理论基础、研究方法、结果、讨论、结论和参考文献等章节。',
                'product_proposal': '产品提案通常包括：概述、市场需求、产品描述、竞争分析、发展计划、营销策略、财务分析和风险评估等章节。',
                'project_proposal': '项目提案通常包括：执行摘要、项目背景、目标、方法、时间表、预算、团队和预期成果等章节。',
                'user_manual': '用户手册通常包括：产品概述、快速入门、基本功能、高级功能、故障排除和常见问题等章节。',
                'technical_manual': '技术手册通常包括：系统概述、架构设计、安装指南、配置、API参考、技术规格和开发指南等章节。'
            };
            
            // 当模板类型改变时更新必需章节建议
            $('#templateType').on('change', function() {
                const templateType = $(this).val();
                
                if (templateType && templateType !== 'custom' && templateExamples[templateType]) {
                    $('#requiredSections').attr('placeholder', templateExamples[templateType]);
                } else {
                    $('#requiredSections').attr('placeholder', '输入必须包含的章节，每行一个');
                }
            });
            
            // 生成模板
            $('#templateForm').on('submit', function(e) {
                e.preventDefault();
                
                const templateType = $('#templateType').val();
                const templateName = $('#templateName').val().trim();
                const templatePurpose = $('#templatePurpose').val().trim();
                const requiredSections = $('#requiredSections').val().trim();
                
                if (!templateType) {
                    alert('请选择模板类型');
                    return;
                }
                
                if (!templateName) {
                    alert('请输入模板名称');
                    return;
                }
                
                // 显示加载动画
                $('#templateSpinner').removeClass('d-none');
                $('#generateTemplateBtn').prop('disabled', true);
                
                // 发送请求生成模板
                $.ajax({
                    url: '/api/generate-template',
                    type: 'POST',
                    data: {
                        template_type: templateType,
                        template_name: templateName,
                        template_purpose: templatePurpose,
                        required_sections: requiredSections
                    },
                    success: function(response) {
                        if (response.template_id) {
                            templateData = response;
                            currentTemplateId = response.template_id;
                            
                            // 显示模板结构
                            displayTemplateStructure(response.template_structure);
                            
                            // 显示模板预览
                            displayTemplatePreview(response.template_preview);
                            
                            // 初始化变量列表
                            templateVariables = response.template_variables || [];
                            displayTemplateVariables();
                            
                            // 启用按钮
                            $('#saveTemplateBtn, #exportDocxBtn, #exportMdBtn, #addVariableBtn').prop('disabled', false);
                        } else {
                            alert('生成模板失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('请求失败: ' + xhr.responseText);
                    },
                    complete: function() {
                        $('#templateSpinner').addClass('d-none');
                        $('#generateTemplateBtn').prop('disabled', false);
                    }
                });
            });
            
            // 显示模板结构
            function displayTemplateStructure(structure) {
                if (!structure) {
                    return;
                }
                
                let html = '<div class="template-structure">';
                
                // 递归构建目录结构
                function buildStructure(items, level = 0) {
                    let result = '';
                    
                    for (const item of items) {
                        const paddingLeft = level * 20;
                        
                        result += `<div class="template-section mb-2" style="padding-left: ${paddingLeft}px">`;
                        result += `<i class="bi bi-${level === 0 ? 'file-earmark-text' : 'dash'} me-2"></i>`;
                        result += `<span class="fw-${level === 0 ? 'bold' : 'normal'}">${item.title}</span>`;
                        result += '</div>';
                        
                        if (item.children && item.children.length > 0) {
                            result += buildStructure(item.children, level + 1);
                        }
                    }
                    
                    return result;
                }
                
                html += buildStructure(structure);
                html += '</div>';
                
                $('#templateStructure').html(html);
            }
            
            // 显示模板预览
            function displayTemplatePreview(preview) {
                if (!preview) {
                    return;
                }
                
                // 将Markdown格式转换为简单HTML
                let html = preview;
                
                // 标题转换
                html = html.replace(/^# (.*?)$/gm, '<h1>$1</h1>');
                html = html.replace(/^## (.*?)$/gm, '<h2>$1</h2>');
                html = html.replace(/^### (.*?)$/gm, '<h3>$1</h3>');
                
                // 变量高亮
                html = html.replace(/\{\{(.*?)\}\}/g, '<span class="badge bg-info">{{$1}}</span>');
                
                // 段落转换
                html = html.replace(/^(?!(#{1,3}|<h[1-3]))(.*?)$/gm, function(match) {
                    if (match.trim() === '') return '<br>';
                    return '<p>' + match + '</p>';
                });
                
                $('#templatePreview').html('<div class="template-preview">' + html + '</div>');
            }
            
            // 显示模板变量
            function displayTemplateVariables() {
                if (!templateVariables || templateVariables.length === 0) {
                    $('#variablesList').html('<div class="text-center py-4 text-muted"><p>还没有添加变量</p></div>');
                    return;
                }
                
                let html = '<div class="table-responsive"><table class="table table-hover">';
                html += '<thead><tr><th>变量名</th><th>描述</th><th>默认值</th><th>操作</th></tr></thead>';
                html += '<tbody>';
                
                for (const variable of templateVariables) {
                    html += '<tr>';
                    html += `<td><code>{{${variable.name}}}</code></td>`;
                    html += `<td>${variable.description || ''}</td>`;
                    html += `<td>${variable.default_value || ''}</td>`;
                    html += `<td><button class="btn btn-sm btn-outline-danger delete-variable" data-variable="${variable.name}"><i class="bi bi-trash"></i></button></td>`;
                    html += '</tr>';
                }
                
                html += '</tbody></table></div>';
                $('#variablesList').html(html);
                
                // 绑定删除按钮事件
                $('.delete-variable').on('click', function() {
                    const variableName = $(this).data('variable');
                    deleteVariable(variableName);
                });
            }
            
            // 删除变量
            function deleteVariable(variableName) {
                if (confirm(`确定要删除变量 {{${variableName}}} 吗？`)) {
                    templateVariables = templateVariables.filter(v => v.name !== variableName);
                    
                    // 更新服务器端数据
                    updateTemplateVariables();
                    
                    // 更新显示
                    displayTemplateVariables();
                }
            }
            
            // 更新服务器端模板变量
            function updateTemplateVariables() {
                if (!currentTemplateId) {
                    return;
                }
                
                $.ajax({
                    url: '/api/update-template-variables',
                    type: 'POST',
                    data: {
                        template_id: currentTemplateId,
                        variables: JSON.stringify(templateVariables)
                    },
                    error: function() {
                        alert('更新变量失败');
                    }
                });
            }
            
            // 打开添加变量模态框
            $('#addVariableBtn').on('click', function() {
                // 清空表单
                $('#variableName, #variableDescription, #variableDefault').val('');
                
                // 显示模态框
                $('#variableModal').modal('show');
            });
            
            // 保存变量
            $('#saveVariableBtn').on('click', function() {
                const name = $('#variableName').val().trim();
                const description = $('#variableDescription').val().trim();
                const defaultValue = $('#variableDefault').val().trim();
                
                if (!name) {
                    alert('请输入变量名');
                    return;
                }
                
                // 检查变量名是否重复
                if (templateVariables.some(v => v.name === name)) {
                    alert('变量名已存在');
                    return;
                }
                
                // 添加变量
                templateVariables.push({
                    name: name,
                    description: description,
                    default_value: defaultValue
                });
                
                // 更新服务器端数据
                updateTemplateVariables();
                
                // 更新显示
                displayTemplateVariables();
                
                // 关闭模态框
                $('#variableModal').modal('hide');
            });
            
            // 保存模板
            $('#saveTemplateBtn').on('click', function() {
                if (!templateData || !currentTemplateId) {
                    alert('请先生成模板');
                    return;
                }
                
                $.ajax({
                    url: '/api/save-template',
                    type: 'POST',
                    data: {
                        template_id: currentTemplateId
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('模板保存成功！');
                        } else {
                            alert('保存失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('请求失败: ' + xhr.responseText);
                    }
                });
            });
            
            // 导出为Word模板
            $('#exportDocxBtn').on('click', function() {
                if (!templateData || !currentTemplateId) {
                    alert('请先生成模板');
                    return;
                }
                
                window.location.href = '/api/export-template-docx/' + currentTemplateId;
            });
            
            // 导出为Markdown
            $('#exportMdBtn').on('click', function() {
                if (!templateData || !currentTemplateId) {
                    alert('请先生成模板');
                    return;
                }
                
                window.location.href = '/api/export-template-md/' + currentTemplateId;
            });
            
            // 模型切换功能
            $('.model-switch').on('click', function(e) {
                e.preventDefault();
                
                const modelType = $(this).data('model');
                
                if (modelType === currentModel) {
                    return; // 已经是当前模型，不需要切换
                }
                
                // 发送切换请求
                $.ajax({
                    url: '/api/switch-model',
                    type: 'POST',
                    data: {
                        model_type: modelType
                    },
                    success: function(response) {
                        if (response.success) {
                            currentModel = modelType;
                            
                            // 显示切换成功消息
                            const modelName = modelType === 'local' ? '本地模型' : '第三方模型';
                            alert(`已切换到${modelName}`);
                        } else {
                            alert('模型切换失败: ' + (response.error || '未知错误'));
                        }
                    },
                    error: function(xhr) {
                        alert('模型切换请求失败: ' + xhr.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html> 